<template>
  <div class="app-container">
    <div>
      <!-- 条件栏 -->
      <NewPageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :slipSelectRequest="slipSelectRequest"
      >
        <template v-slot:filter-time>
          <el-date-picker
            @change="timeChange"
            v-model="time"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            :shortcuts="$fn.pickerDateOptionsNoCurDateFn().shortcuts"
            :disabled-date="datePickerOptions.disabledDate"
            align="right"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </template>
        <template v-slot:filter-productId>
          <el-input
            class="not-mongolia"
            type="input"
            :disabled="true"
            placeholder="请选择产品"
            v-model="productNameList"
          >
            <template #append>
              <el-icon @click="openProductWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:filter-productionDate>
          <el-date-picker
            @change="productionDateChange"
            v-model="productionDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            :shortcuts="$fn.pickerDateOptionsFn().shortcuts"
            align="right"
            start-placeholder="生产日期"
            end-placeholder="生产日期"
          ></el-date-picker>
        </template>
        <template v-slot:filter-validityDate>
          <el-date-picker
            @change="validityDateChange"
            v-model="validityDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            :shortcuts="$fn.pickerOptionsFn()"
            align="right"
            start-placeholder="失效日期"
            end-placeholder="失效日期"
          ></el-date-picker>
        </template>
      </NewPageFilter>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"></NewPageFilter>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :checkBox="false"
        :handle="tableInfo.handle"
        :tab-index="true"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
      >
        <template v-slot:col-storeAmount="scope">
          <span
            v-if="$permission('warehouseAffair:list')"
            class="slip-edit"
            @click="showDetail(scope.row, '1')"
            >{{ $fn.TripartiteMethod(scope.row.storeAmount || '-') }}</span
          >
          <span v-else>{{
            $fn.TripartiteMethod(scope.row.storeAmount || '-')
          }}</span>
        </template>
        <template v-slot:col-exportAmount="scope">
          <span
            v-if="$permission('warehouseAffair:list')"
            class="slip-edit"
            @click="showDetail(scope.row, '0')"
            >{{ $fn.TripartiteMethod(scope.row.exportAmount || '-') }}</span
          >
          <span v-else>{{
            $fn.TripartiteMethod(scope.row.exportAmount || '-')
          }}</span>
        </template>
      </TableContainer>
    </div>
    <NewSelectProduct
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      v-model:query="productInfo.query.queryMap"
      :api="productInfo.api"
      :saveEmpty="true"
      :query-params="productInfo.query.queryParams"
      :show-price="productInfo.priceShow"
      @callback="selectProduct"
    />
  </div>
</template>

<script setup name="warehouseInvoicingSummary">
import { getDepotAll, getDeptAll, getSupplierAll } from '@/api/core'
import {
  purchaseSaleStorageQueryPageByDepot,
  purchaseSaleStorageQueryPrintByDepot,
  purchaseSaleStorageQueryExcelByDepot,
  purchaseSaleCoreProductQuery,
} from '@/api/dataQuery'
import { fatchTemplateByCode } from '@/api/base'

import moment from 'moment'
const { proxy } = getCurrentInstance()
const productNameList = ref('')
const time = ref(null)
const datePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > +new Date() - 3600 * 1000 * 24
  },
})
const validityDate = ref(null)
const productionDate = ref(null)
const slipSelectRequest = ref(true)
const filterInfo = ref({
  query: {
    isPagerByPrint: false, //打印是否分页
    isPagerByExport: false, //导出是否分页
    startDate: '',
    endDate: '',
    depotIdMult: '',
    deptIdMult: '',
    productionDateGreater: '',
    productionDateLesser: '',
    validityDateGreater: '',
    validityDateLesser: '',
  },
  searchList: [
    { label: '时间', value: 'time', slot: true },

    {
      componentType: 'slip-select',
      label: '仓库',
      value: 'depotIdMult',
      api: getDepotAll,
      query: {
        status: '1',
        depotAuth: 'id',
        searchType: 'depot',
        useTypeId: '1',
      },
      multiple: true,
      event: search,
    },
    {
      componentType: 'slip-select',
      label: '部门',
      value: 'deptIdMult',
      api: getDeptAll,
      query: {
        status: '1',
        deptAuth: 'id',
        searchType: 'dept',
      },
      multiple: true,
      event: search,
    },
    {
      slot: true,
      label: '产品',
      value: 'productId',
    },
    { label: '生产日期', value: 'productionDate', slot: true },
    { label: '失效日期', value: 'validityDate', slot: true },
    {
      componentType: 'input',
      label: '产品批号',
      value: 'batchNumber',
      event: search,
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      asValue: 'isConsignBusiness',
      componentType: 'select-model',
      code: 'yes_or_no',
      event: search,
    },
    {
      label: '是否暂估入库',
      value: 'isEstimationStockBusinessValue',
      asValue: 'isEstimationStockBusiness',
      componentType: 'select-model',
      code: 'yes_or_no',
      event: search,
    },
    {
      label: '供应商',
      value: 'supplierIdMult',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: { sort: 'create_time desc' },
      clearable: true,
      multiple: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      event: search,
    },
    {
      label: '入库批次号',
      value: 'storeBatchNumber',
      componentType: 'input',
      event: search,
    },
  ],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    { type: 'button', label: '打印', event: print },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: true,
    },
  ],
})

const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: purchaseSaleStorageQueryPageByDepot,
  data: [],
  selections: [],
  fieldList: [
    { label: '仓库', value: 'depotName' },
    {
      label: '期初总金额',
      value: 'beginAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '入库总金额',
      value: 'storeAmount',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '出库总金额',
      value: 'exportAmount',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '净总金额',
      value: 'netAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '期末总金额',
      value: 'endAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '待入库总金额',
      value: 'pendStoreAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
const productInfo = ref({
  visible: false,
  api: purchaseSaleCoreProductQuery,
  priceShow: true,
  query: {
    queryMap: {},
    queryParams: {},
  },
  searchList: [],
})
const productList = ref([])
function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function exportExcel() {
  purchaseSaleStorageQueryExcelByDepot(
    proxy.$fn.delEmptyAttribute(filterInfo.value.query)
  ).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function print() {
  fatchTemplateByCode({
    resourceCode: 'warehouseInvoicingSummary:printList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp)
    }
  })
}
function getPrintData(temp) {
  let params = {
    ...filterInfo.value.query,
  }
  purchaseSaleStorageQueryPrintByDepot(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.startDate = val[0]
    filterInfo.value.query.endDate = val[1]
  } else {
    filterInfo.value.query.startDate = ''
    filterInfo.value.query.endDate = ''
  }
}
function productionDateChange(val) {
  if (val && val.length) {
    filterInfo.value.query.productionDateLesser = val[0]
    filterInfo.value.query.productionDateGreater = val[1]
  } else {
    filterInfo.value.query.productionDateLesser = ''
    filterInfo.value.query.productionDateGreater = ''
  }
}
function validityDateChange(val) {
  if (val && val.length) {
    filterInfo.value.query.validityDateLesser = val[0]
    filterInfo.value.query.validityDateGreater = val[1]
  } else {
    filterInfo.value.query.validityDateLesser = ''
    filterInfo.value.query.validityDateGreater = ''
  }
}
function showDetail(row, type) {
  let operateTime = null
  if (filterInfo.value.query.startDate) {
    operateTime =
      filterInfo.value.query.startDate +
      ' 00:00:00' +
      ',' +
      filterInfo.value.query.endDate +
      ' 23:59:59'
  }
  let validityDate = null
  if (filterInfo.value.query.validityDateGreater) {
    validityDate =
      filterInfo.value.query.validityDateLesser +
      ',' +
      filterInfo.value.query.validityDateGreater
  }
  let productionDate = null
  if (filterInfo.value.query.productionDateGreater) {
    productionDate =
      filterInfo.value.query.productionDateLesser +
      ',' +
      filterInfo.value.query.productionDateGreater
  }
  proxy.$router.push({
    name: 'warehouseAffair',
    params: {
      query: JSON.stringify({
        queryMap: {
          deptId: {
            queryType: 'IN',
            value: row.deptId,
          },
          depotId: {
            queryType: 'IN',
            value: row.depotId,
          },
          productId: {
            queryType: 'IN',
            value: filterInfo.value.query.productIdMult,
          },
          operateTime: {
            queryType: 'BETWEEN',
            value: operateTime,
          },
          exportStoreType: {
            queryType: 'IN',
            value: type,
          },
          batchNumber: {
            queryType: 'ALL_LIKE',
            value: filterInfo.value.query.batchNumber,
          },
          validityDate: {
            queryType: 'BETWEEN',
            value: validityDate,
          },
          productionDate: {
            queryType: 'BETWEEN',
            value: productionDate,
          },
          isConsignBusiness: {
            queryType: 'IN',
            value: filterInfo.value.query.isConsignBusiness,
          },
          supplierId: {
            queryType: 'IN',
            value: filterInfo.value.query.supplierIdMult,
          },
        },
      }),
    },
  })
}
//选择产品
function selectProduct(rows) {
  if (rows) {
    productList.value = rows
    filterInfo.value.query.productIdMult = rows
      .map((item) => item.id)
      .toString()
    productNameList.value = rows.map((item) => item.commonName).toString()
  } else {
    productList.value = []
    filterInfo.value.query.productIdMult = ''
    productNameList.value = ''
  }
}
function openProductWindow() {
  const { depotIdMult, deptIdMult, startDate, endDate } = filterInfo.value.query

  if (!startDate || !endDate) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请选择查询时间！',
    })
    return
  }
  productInfo.value.query.queryParams.depotIdMult = depotIdMult
  productInfo.value.query.queryParams.deptIdMult = deptIdMult
  productInfo.value.query.queryParams.startDate = startDate
  productInfo.value.query.queryParams.endDate = endDate
  productInfo.value.visible = true
}

filterInfo.value.searchList.forEach((item) => {
  item.show = true
})

onMounted(() => {
  proxy.$nextTick(() => {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    end.setTime(end - 3600 * 1000 * 24)
    filterInfo.value.query.startDate = moment(start).format('YYYY-MM-DD')
    filterInfo.value.query.endDate = moment(end).format('YYYY-MM-DD')
    time.value = [
      moment(start).format('YYYY-MM-DD'),
      moment(end).format('YYYY-MM-DD'),
    ]
    getList()
  })
})
</script>

<style scoped lang="scss">
:deep(.el-tag) {
  margin: 2px 5px 2px 0;
}
</style>
